local kanwu = fk.CreateSkill{
  name = "xiaobai__kanwu",
  dynamic_desc = function (self, player, lang)
    local limit = player:getMark("xiaobai__kanwu_limit")
    local use_times = player:getMark("xiaobai__kanwu_usedTimes-round")
    if limit > 0 then
      return "xiaobai__kanwu_dynamic:"..(limit)..":"..(limit - use_times)
    end
  end
}

Fk:loadTranslationTable{
  ["xiaobai__kanwu"] = "勘物",
  [":xiaobai__kanwu"] = "每轮开始时，你可以令所有角色轮流弃置一张牌（无牌跳过），直到类型与花色均出现相同；"..
    "本轮限X次，符合这一组合的牌进入弃牌堆后，你可以获得之（X为此法弃置的牌数）。",

  [":xiaobai__kanwu_dynamic"] = "每轮开始时，你可以令所有角色轮流弃置一张牌（无牌跳过），直到类型与花色均出现相同；"..
    "本轮限 {1} 次，符合这一组合的牌进入弃牌堆后，你可以获得之（还有 {2} 次）。",
  ["#xiaobai__kanwu"] = "勘物：你须弃置一张牌",

  ["#xiaobai__kanwu_aquire"] = "勘物：你可以获得 %arg",
  ["@xiaobai__kanwu_suits"] = "勘物花色",
  ["@xiaobai__kanwu_types"] = "勘物类型",
}

local U = require "packages.utility.utility"

---@param target ServerPlayer
---@return ServerPlayer?
local getNextHaveCard = function (target)
  local next_target = target:getNextAlive() ---@type ServerPlayer
  while next_target ~= target do
    if not table.find(next_target:getCardIds("he"), function (c)
      return not next_target:prohibitDiscard(c)
    end) then
      next_target = next_target:getNextAlive() ---@type ServerPlayer
    else
      return next_target
    end
  end
end

kanwu:addEffect(fk.RoundStart, {
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self)
  end,
  times = function(self, player)
    if player:getMark("xiaobai__kanwu_limit") > 0 then
      return player:getMark("xiaobai__kanwu_limit") - player:getMark("xiaobai__kanwu_usedTimes-round")
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local now_target = getNextHaveCard(room:getAlivePlayers()[1]:getLastAlive())
    if not now_target then 
      now_target = room:getAlivePlayers()[1]:getLastAlive()
      if not table.find(now_target:getCardIds("he"), function (c)
        return not now_target:prohibitDiscard(c)
      end) then
        return
      end
    end
    local card_results = {} ---@type integer[]
    
    local types = {}
    local repeativeType = {}
    
    local suits = {}
    local repeativeSuit = {}
    while true do
      local cards = room:askToDiscard(now_target, {
        min_num = 1,
        max_num = 1,
        cancelable = false,
        skill_name = kanwu.name,
        skip = true,
        include_equip = true,
        prompt = "#xiaobai__kanwu",
      })
      room:throwCard(cards, kanwu.name, now_target, player)
      table.insert(card_results, cards[1])
      local t =  getNextHaveCard(now_target)
      if t then
        now_target = t
      else
        break
      end
      local card = Fk:getCardById(cards[1])
      if not table.contains(suits, card.suit) then
        table.insert(suits, card.suit)
      else
        table.insertIfNeed(repeativeSuit, U.ConvertSuit( card.suit, "int", "sym"))
      end
      if not table.contains(types, card.type) then
        table.insert(types, card.type)
      else
        table.insertIfNeed(repeativeType, card:getTypeString().."_char")
      end
      if #repeativeSuit > 0 and #repeativeType > 0 then
        break
      end
    end

    if #repeativeSuit > 0 and #repeativeType > 0 then
      room:setPlayerMark(player, "@xiaobai__kanwu_suits", repeativeSuit)
      room:setPlayerMark(player, "@xiaobai__kanwu_types", repeativeType)
      room:setPlayerMark(player, "xiaobai__kanwu_limit", #card_results)
    end
  end,
})

kanwu:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(kanwu.name) and ((player:getMark("xiaobai__kanwu_limit") - player:usedEffectTimes(self.name, Player.HistoryRound)) > 0)
  end,
  on_trigger = function (self, event, target, player, data)
    local suits = player:getTableMark("@xiaobai__kanwu_suits")
    local types = player:getTableMark("@xiaobai__kanwu_types")
    for _, move in ipairs(data) do
      if move.toArea ==  Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          local c = Fk:getCardById(info.cardId)
          if table.contains(suits, U.ConvertSuit(c.suit, "int", "sym")) and table.contains(types, c:getTypeString().."_char") then
            self:doCost(event, target, player, info.cardId)
          end
        end
      end      
    end
  end,
  on_cost = function (self, event, target, player, data)
    local card = Fk:getCardById(data)
    event:setCostData(self, {card = card})
    return player.room:askToSkillInvoke(player, {skill_name = kanwu.name, prompt = "#xiaobai__kanwu_aquire:::"..card:toLogString()})
  end,
  on_use = function (self, event, target, player, data)
    local card = event:getCostData(self).card
    player.room:obtainCard(player, card, false, fk.ReasonPrey, player, kanwu.name)
    player.room:addPlayerMark(player, "xiaobai__kanwu_usedTimes-round", 1)
  end
})


return kanwu